package org.mianshi.zuoyebang;

import java.util.ArrayList;
import java.util.List;

public class 有效的括号 {
    public static void main(String[] args) {
        int n = 3; // 括号的对数
        List<String> result = generateParentheses(n);
        System.out.println(result);
    }

    public static List<String> generateParentheses(int n) {
        List<String> result = new ArrayList<>();
        generate(result, "", 0, 0, n);
        return result;
    }

    private static void generate(List<String> result, String current, int open, int close, int max) {
        // 如果当前字符串长度等于括号对数的两倍，添加到结果中
        if (current.length() == max * 2) {
            result.add(current);
            return;
        }

        // 如果可以添加左括号
        if (open < max) {
            generate(result, current + "(", open + 1, close, max);
        }

        // 如果可以添加右括号
        if (close < open) {
            generate(result, current + ")", open, close + 1, max);
        }
    }
}